package cn.iocoder.yudao.framework.common.util.ipa;

import com.dd.plist.NSArray;
import com.dd.plist.NSDictionary;
import com.dd.plist.PropertyListParser;
import org.bouncycastle.cms.CMSSignedData;

import java.io.File;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author liujq
 * @date 20241224 11:35
 */
public class MbUtil {
    /**
     * 解析mobileprovision文件
     * @param provisionPath 文件路径
     * @return 解析后的数据Map
     */
    public static Map<String, Object> parseProvisionFile(String provisionPath) throws Exception {
        // 读取文件
        byte[] bytes = Files.readAllBytes(new File(provisionPath).toPath());

        // 解析CMS格式
        CMSSignedData signedData = new CMSSignedData(bytes);
        byte[] content = (byte[]) signedData.getSignedContent().getContent();

        // 解析plist内容
        NSDictionary rootDict = (NSDictionary) PropertyListParser.parse(content);

        Map<String, Object> result = new HashMap<>();

        // 获取开发者名称
        result.put("teamName", rootDict.get("TeamName").toString());

        // 获取UDID列表
        NSArray provisionedDevices = (NSArray) rootDict.get("ProvisionedDevices");
        List<String> udids = new ArrayList<>();
        if (provisionedDevices != null) {
            for (int i = 0; i < provisionedDevices.count(); i++) {
                udids.add(provisionedDevices.objectAtIndex(i).toString());
            }
        }
        result.put("udid", udids.get(0));

        // 获取其他常用信息
        result.put("appIdName", rootDict.get("AppIDName").toString());
        result.put("teamIdentifier", rootDict.get("TeamIdentifier").toString());
        result.put("creationDate", rootDict.get("CreationDate").toString());
        result.put("expirationDate", rootDict.get("ExpirationDate").toString());
        result.put("teamName", rootDict.get("TeamName").toString());

        return result;
    }

    public static void main(String[] args) throws Exception {
        Map<String, Object> stringObjectMap = parseProvisionFile("E:\\51158c37-be16-4b05-bb2a-c08093d542c7.mobileprovision");
        System.out.println(stringObjectMap);

    }

}
